package com.lhczf.lucenedb;

import com.lhczf.lucenedb.bean.SystemConfig;
import com.lhczf.lucenedb.consumer.BackUpDataConsumer;
import com.lhczf.lucenedb.consumer.CleanData;
import com.lhczf.lucenedb.consumer.WrapThreadFactory;
import com.lhczf.lucenedb.service.LuceneDbServer;
import com.lhczf.lucenedb.util.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

/**
 * @author: 刘华春
 * @date: 2019/2/6
 */
@SpringBootApplication
@Slf4j
public class LucenedbApplication {

    public static void main(String[] args) {
        SpringApplication.run(LucenedbApplication.class, args);
        LuceneDbServer server = BeanUtil.getInstance().getBean(LuceneDbServer.class);
        SystemConfig systemConfig = BeanUtil.getInstance().getBean(SystemConfig.class);
        server.init(systemConfig);

        server.beginDataProduction(systemConfig);
        server.beginDataConsumer(systemConfig);

        log.info("备份线程的运行周期为：{}分钟。", systemConfig.getBackUpPeriod());
        ThreadFactory nameFactory = new WrapThreadFactory("backup_luceneDB_thread");
        ScheduledExecutorService backUpScheduled = new ScheduledThreadPoolExecutor(1, nameFactory);
        Runnable backUpRunnable = new BackUpDataConsumer();
        backUpScheduled.scheduleAtFixedRate(backUpRunnable, 10, 10, TimeUnit.MINUTES);

        log.info("清理线程的运行周期为：{}分钟。", systemConfig.getCleanPeriod());
        ThreadFactory cleanFactory = new WrapThreadFactory("clean_luceneDB_thread");
        ScheduledExecutorService cleanScheduled = new ScheduledThreadPoolExecutor(1, cleanFactory);
        Runnable cleanRunnable = new CleanData();
        cleanScheduled.scheduleWithFixedDelay(cleanRunnable, 0, systemConfig.getCleanPeriod(), TimeUnit.MINUTES);
    }
}

